package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.properties.MinIOProperties;
import com.atguigu.spzx.manager.service.FileUploadService;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.Date;

/**
 * @Author：tzl
 * @Date：2024/1/26 17:02
 * @description: 文件上传
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinIOProperties minIOProperties;

    @Override
    public String fileUploadService(MultipartFile file) {
        String fileUrl;

        try {
            // 创建一个Minio的客户端对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minIOProperties.getEndpointUrl())
                    .credentials(minIOProperties.getAccessKey(), minIOProperties.getSecreKey())
                    .build();

            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minIOProperties.getBucketName()).build());
            // 如果不存在，那么此时就创建一个新的桶
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minIOProperties.getBucketName()).build());
            } else {  // 如果存在打印信息
                System.out.println("Bucket 'spzx-bucket' already exists.");
            }

            // 日期作为文件夹
            // uuid作为文件名
            String dateString = DateUtil.format(new Date(), "yyyyMMdd");
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String filename = dateString + "/" + uuid;
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minIOProperties.getBucketName())
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .object(filename)
                    .build();
            minioClient.putObject(putObjectArgs);

            // 构建fileUrl
            fileUrl = minIOProperties.getEndpointUrl() + "/" + minIOProperties.getBucketName() + "/" + filename;
            System.out.println(fileUrl);

        } catch (Exception e) {
            e.printStackTrace();
            throw new GuiguException(ResultCodeEnum.ERROR);
        }

        return fileUrl;

    }
}
